/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.izu.mytruco.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Ademar
 */
public class CommunicatorClient implements Runnable {

    protected Socket socket;
    protected ClientListener listener;
    protected BufferedWriter writer;
    protected BufferedReader reader;
    protected Thread thread;

    public CommunicatorClient(ClientListener listener) throws UnknownHostException, IOException {
        this.listener = listener;
        this.socket = new Socket("localhost", 8888);
        this.writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));
        this.reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
        this.thread = new Thread(this);
        this.thread.start();
    }

    public void run() {
        while (true) {
            try {
                listener.messageReceived(reader.readLine());
            } catch (IOException ex) {
                Logger.getLogger(CommunicatorClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void sendMessage(String message) throws IOException {
        this.writer.write(message);
        this.writer.newLine();
        this.writer.flush();
    }
}
